<html>
<?php

require_once('connection.php');
/*function to create table in cs2102_db*/
function createCustomerTable(){
	mysql_select_db("cs2102_db");
	
	$sql = "CREATE TABLE Customer(
			cid INT AUTO_INCREMENT,
			name VARCHAR(50),
			phoneNo CHAR(8) NOT NULL,
			email VARCHAR(128) UNIQUE NOT NULL,
			password CHAR(8) NOT NULL,
			PRIMARY KEY(cid)
		)";
	if (mysql_query($sql)){
		echo "CustomerTable created";
	}else{
		echo "CustomerTable is not created";
		die('Could not create: ' . mysql_error());
	}
}

/*To insert a tuple in Customer table. Input is taken from CustomerInput.php*/
function insertTuple(){
	$password = $_POST["password"];
	$password2 = $_POST["password2"];
	if ($password != $password2){
		$errmsg_arr[] = 'Please enter your password again.';
		$_SESSION['ERRMSG'] = $errmsg_arr;
		session_write_close();
		header("location: cus_reg.php");
		exit();
	}
	
	$sql="INSERT INTO Customer (name, phoneNo, email, password)
		VALUES('$_POST[name]','$_POST[phoneNo]','$_POST[email]','$_POST[password]')";
	if (!mysql_query($sql)){
		header("location: cus_reg.php");
		exit();
		return false;
	}else{
		echo "Sign up successful!";
		return true;
	}
}
function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
}

function changePassword(){
	session_start();
	$name = clean($_SESSION['SESS_FIRST_NAME']);
	$new_password = clean($_POST['new_password']);
	$sql="UPDATE customer
	      SET customer.password = '$new_password'
		  WHERE customer.name = '$name'";
	if (!mysql_query($sql)){
		die('Error: '.mysql_error());
	}else{
		session_regenerate_id();
		$_SESSION['SESS_FIRST_NAME'] = $name;
		$_SESSION['SESS_LAST_NAME'] = $new_password;
		session_write_close();
	}
}
function modify(){
	session_start();
	$cid = $_SESSION['SESS_CID'];
	$new_name = clean($_POST['new_name']);
	$new_phoneNo = clean($_POST['new_phoneNo']);
	$new_email = clean($_POST['new_email']);
	$updateCustomerInfo = "UPDATE customer
			SET name = '$new_name', phoneNo = '$new_phoneNo', email = '$new_email'
			WHERE cid = '$cid'";
	if (!mysql_query($updateCustomerInfo)){
		die('Error: '.mysql_error());
	}
}

/*-----------------------Start to execute from this point------------------------------*/

/*select our database cs2102_bd*/

/*
if (isExistTable("customer")==NULL){
	createCustomerTable();
}*/

switch($_POST['method'])
{
	case 'insert':
		insertTuple();
		unset($_POST);
		header("location: cus_login.php");
		break;
	case 'delete':
		deleteTuple();
		unset($_POST);
		break;
	case 'change_password':
	    changePassword();
		unset($_POST);
		header("location: cus_profile.php");
		break;
	case 'modify':
		echo modify();
		unset($_POST);
		header("location: cus_profile.php");
		break;
	DEFAULT:
		echo 'error';
}

mysql_close();
?>
</html>